<template>
  <div class="box">
    <el-upload
      class="avatar-uploader"
      :action="baseURL + '/question/upload'"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />

    </el-upload>
    <div v-if="value" class="mask" @click="delEvent">
      <i class="el-icon-delete" @click="delEvent" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      //   imageUrl: '',
      baseURL: process.env.VUE_APP_BASE_API
    }
  },

  methods: {
    handleAvatarSuccess(res, file) {
      this.$emit('input', this.baseURL + '/' + res.data.url)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    delEvent() {
      this.$emit('input', '')
    }
  }
}
</script>
  <style lang="scss" scoped>

  .box{
    width: 178px;
    height: 178px;
    border-radius: 6px;
    position: relative;
    border: 1px dashed #d9d9d9;
    overflow: hidden;
    &:hover .mask{
      display: block;
    }
    .mask  {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0,.5);
      display: none;
      line-height: 178px;
      text-align: center;
      font-size: 28px;
      color:#fff;
      z-index: 999;
  }
  }
  .avatar-uploader ::v-deep .el-upload {
    cursor: pointer;
  }
  .avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px
  }
</style>
